import axios from 'axios'
import { ElMessage } from "element-plus";

let apiKey = ''
const modelR1 = 'deepseek-r1'
const modelV3 = 'deepseek-v3'


const url = import.meta.env.VITE_APP_ENV == "development" ? '/deepseek/compatible-mode/v1/chat/completions#' : 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions'

export const fast_gpt = async (userText) => {
  try {
    const result = await axios.post(
      url,
      {
        model: model,
        messages: [
          { role: 'system', content: '' },
          { role: 'user', content: userText },
        ],
        max_tokens: 4096,
        temperature: 0.1,
        stream: false,   // 不是流格式的必须为false
      },
      {
        headers: {
          Authorization: `Bearer ${apiKey}`,   // 对应你的key
          'Content-Type': 'application/json',  // 指定返回json格式的
        },
      },
    );
    return extractJsonFromText(result?.choices[0].message.content) || result?.choices[0].message.content;
  } catch (error) {
    console.error('请求错误：', error);
  } finally {
  }
};

export const fast_gptStream = async (model_type, userText, onDataChunk, onComplete) => {
  let isStopped = false; // 添加一个标志来控制停止生成
  const abortController = new AbortController();
  const signal = abortController.signal;
  let reader;
  try {
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${apiKey}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        model: model_type == 'r1' ? modelR1 : modelV3,
        messages: [
          { role: 'system', content: '' },
          { role: 'user', content: userText },
        ],
        temperature: 1,
        stream: true,
      }),
      signal: signal, // 添加信号
    });

    if (!response.ok) {
      if (response.status === 500) {
        ElMessage.error('AI接口繁忙，请稍后操作');
        onComplete();
      } else {
        ElMessage.error('请求失败:',response.status, response.statusText);
        onComplete();
      }
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    if (!response.body) {
      throw new Error('服务器未返回流数据');
    }

    reader = response.body.getReader();
    const decoder = new TextDecoder('utf-8');
    let buffer = '';

    while (true) {
      if (isStopped) {
        await reader.cancel(); // 停止读取流
        console.log('Stream stopped');
        break;
      }

      const { done, value } = await reader.read();
      if (done) break;

      const chunk = decoder.decode(value, { stream: true });
      buffer += chunk;

      const lines = buffer.split('\n');
      buffer = lines.pop();

      for (const line of lines) {
        if (line.startsWith('data: ')) {
          const jsonStr = line.slice(6).trim();
          if (jsonStr !== '[DONE]') {
            try {
              const jsonData = JSON.parse(jsonStr);
              const content = jsonData?.choices[0]?.delta?.content || '';
              if (content) {
                onDataChunk(content);
              }
            } catch (error) {
              console.error('解析 JSON 数据失败:', error, line);
            }
          } else {
            onComplete(); // 生成完成时调用回调
            break;
          }
        }
      }
    }
  } catch (error) {
    ElMessage.error('AI接口繁忙，请稍后操作');
    onComplete();
    // console.error('流式数据请求失败:', error);
  } finally {
    if (!isStopped) {
      onComplete(); // 确保在任何情况下都能调用完成回调
    }
  }

  // 提供一个方法来停止生成
  return {
    stop: () => {
      isStopped = true;
      abortController.abort(); // 取消请求
      reader.cancel();
      console.log('Stop method called');
    }
  };
};

export const setToken = async (newApiKey) => {
  apiKey = newApiKey;
};